package czk.concrent.reentrantLock;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/5/31 17:50
 */
// 不同休息室的唤醒
public class Test4 {
    // 有没有烟
    static volatile boolean hasCigarettes=false;
    // 有没有外卖
    static volatile boolean hasTakeOut=false;
    // 锁对象
    private static ReentrantLock lock=new ReentrantLock();

    // 休息室一 区分于syn，syn只有一个休息室
    private static Condition condition1 = lock.newCondition();
    // 休息室二 区分于syn，syn只有一个休息室
    private static Condition condition2=lock.newCondition();
    public static void main(String[] args) {

       // 线程一 烟
        new Thread(()->{
            // 获取锁
            lock.lock();
            try {
                while (!hasCigarettes){
                    System.out.println("没有香烟，继续等待");
                    try {
                        condition1.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("有烟了，可以干活了");
            }finally {
                lock.unlock();
            }

        }).start();
        new Thread(()->{
            lock.lock();
            try {
                while (!hasTakeOut){
                    System.out.println("没有外卖，等待");
                    try {
                        condition2.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("有外卖了，可以干活了");
            }finally {
                // 释放锁
                lock.unlock();
            }

        }).start();
        // 线程三，送外卖
        new Thread(()->{
            // 送烟
            lock.lock();
            try {
                hasCigarettes=true;
                // 唤醒休息室一
                System.out.println("唤醒等烟线程");
                condition1.signal();
            }finally {
                lock.unlock();
            }
        }).start();
        new Thread(()->{
            // 送外卖
            lock.lock();
            try {
                hasTakeOut=true;
                // 唤醒休息室二的线程
                System.out.println("唤醒等外卖线程");
                condition2.signal();
            }finally {
                lock.unlock();
            }
        }).start();
    }
}
